const request = require('request');
const {
    baseUrl
} = require('../config/api.conf');

// promise 原型链上添加 finally 方法
Promise.prototype.finally = function (full, fail) {
    this.then(full, fail).catch(err => {
        setTimeout(() => {
            throw err;
        }, 0)
    })
};

//重写 request 方法
exports.$request = function(config) {
    config = config || {};
    const BASE_URL = config.baseUrl || baseUrl;
    return new Promise((resolve, reject) => {
        const params = {
            timeout: 20000,
            method: config.method || 'get',
            url: BASE_URL + config.url || '',
            headers: config.headers || {}
        };
        // post请求, contentType: application/json
        if(config.headers &&
            config.headers['content-Type'] &&
            config.headers['content-Type'].includes('application/json')){
            params.body = JSON.stringify(config.data || {})
        }else{
            params.qs = config.data || {}
        }
        request(params, function (err, response, body) {
            if(err){
                resolve("{}")
            }else{
                resolve(body)
            }
        })
    });
};




